package cn.edu.java.thread.四种实现方式;

import java.util.concurrent.*;

/**
 * newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
 * newFixedThreadPool  创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。
 * newScheduledThreadPool 创建一个可定期或者延时执行任务的定长线程池，支持定时及周期性任务执行。
 * newCachedThreadPool 创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。
 */
public class ThreadPoolDemo {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();
        ExecutorService fixedThreadPool = Executors.newFixedThreadPool(2);
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 4, 60L, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

        for (int i = 0; i < 100; i++) {
            int finalI = i;
            Runnable runnable = () -> System.out.println("线程名称：" + Thread.currentThread().getName() + " " + finalI);
            cachedThreadPool.submit(runnable);
            fixedThreadPool.submit(runnable);
            singleThreadExecutor.submit(runnable);
            scheduledExecutorService.submit(runnable);
            threadPoolExecutor.execute(runnable);
        }

        cachedThreadPool.shutdown();
        fixedThreadPool.shutdown();
        singleThreadExecutor.shutdown();
        scheduledExecutorService.shutdown();
        threadPoolExecutor.shutdown();
    }
}
